package com.gitee.form_token.config;

import com.gitee.form_token.common.RespUtil;
import com.gitee.form_token.common.Result;
import com.gitee.form_token.token.JwtAuthenticationFilter;
import com.gitee.form_token.service.MyUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.*;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Slf4j
@Configuration
@EnableMethodSecurity
public class SecurityWebConfig {

    @Resource
    private MyUserDetailsService userDetailsService;

    @Resource
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    // 加密方式一
    // @Bean
    // public static NoOpPasswordEncoder passwordEncoder() {
    //     return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    // }

    // 加密方式二
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 身份验证 -- 实现
    @Bean
    public AuthenticationManager authenticationManager() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();

        // 配置基于数据库认证的UserDetailsService对象
        provider.setUserDetailsService(userDetailsService);

        // 创建并返回认证管理器对象(实现类ProviderManager)
        return new ProviderManager(provider);
    }

    // 免鉴权 -- 白名单
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        String[] whiteList = {
                "/", "/home", "/*.ico", "/*.html",
                "**/webjars/**", "**/swagger-ui/**", "**/v3/api-docs/**", "**/doc.html"
        };
        return web -> web.ignoring().antMatchers(whiteList);
    }

    // 过滤器链 -- web端
    @Bean
    public SecurityFilterChain webFilterChain(HttpSecurity http) throws Exception {

        commonHttpSetting(http);

        http.authorizeHttpRequests(authz -> authz
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers("/assets/**").permitAll()
                .antMatchers("/auth/**").permitAll()
                .mvcMatchers("/app/**").permitAll()
                .mvcMatchers("/error").permitAll()
                .anyRequest().authenticated()
        );

        http.exceptionHandling(exception -> {
            // exception.authenticationEntryPoint(myAuthenticationEntryPoint);
            // exception.accessDeniedHandler(myAccessDeniedHandler);
            exception.authenticationEntryPoint((request, response, authException) -> {
                String errorMessage;
                if (authException instanceof AuthenticationCredentialsNotFoundException) {
                    errorMessage = "未认证";
                } else if (authException instanceof BadCredentialsException) {
                    errorMessage = "认证异常";
                } else if (authException instanceof InsufficientAuthenticationException) {
                    errorMessage = "无效认证";
                } else {
                    errorMessage = "认证失败：" + authException.getMessage();
                }
                log.error("认证异常: {}", errorMessage, authException);
                RespUtil.writer(response, Result.fail(errorMessage, 401));
            });
            exception.accessDeniedHandler((request, response, accessDeniedException) -> {
                System.out.println("403===" + accessDeniedException.getMessage());
                RespUtil.writer(response, Result.fail("权限异常", 403));
            });
        });

        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    // 禁用默认Filter
    private void commonHttpSetting(HttpSecurity http) throws Exception {

        http.sessionManagement(AbstractHttpConfigurer::disable)
                .headers(head -> head.frameOptions().disable())
                .anonymous(AbstractHttpConfigurer::disable)
                .httpBasic(AbstractHttpConfigurer::disable)
                .formLogin(AbstractHttpConfigurer::disable)
                .logout(AbstractHttpConfigurer::disable)
                .csrf(AbstractHttpConfigurer::disable)
                .cors(Customizer.withDefaults());

    }
}
